import { ElMessage } from 'element-plus';
import JSZip from 'jszip'

export function downloadFile(data: Blob | string, fileName: string) {
  try {
    const getMimeType = (filename: string) => {
      const ext = filename.split('.').pop()?.toLowerCase();
      switch (ext) {
        case 'zip':
          return 'application/zip';
        case 'pdf':
          return 'application/pdf';
        case 'json':
          return 'application/json';
        case 'txt':
          return 'text/plain';
        case 'csv':
          return 'text/csv';
        case 'xml':
          return 'application/xml';
        case 'doc':
        case 'docx':
          return 'application/msword';
        case 'xls':
        case 'xlsx':
          return 'application/vnd.ms-excel';
        case 'ppt':
        case 'pptx':
          return 'application/vnd.ms-powerpoint';
        case 'png':
          return 'image/png';
        case 'jpg':
        case 'jpeg':
          return 'image/jpeg';
        case 'gif':
          return 'image/gif';
        default:
          return 'application/octet-stream'; // 默认二进制流
      }
    };

    const mimeType = getMimeType(fileName);
    let blob: Blob;

    if (typeof data === 'string') {
      blob = new Blob([data], { type: mimeType });
    } else {
      blob = data;
    }

    // 检查 JSZip 是否可用，并且文件是zip类型
    if (mimeType === 'application/zip' && typeof JSZip !== 'undefined') {
      blob.arrayBuffer().then((arrayBuffer: ArrayBuffer) => {
        // 尝试解压
        JSZip.loadAsync(arrayBuffer).then((zip) => {
          return zip.generateAsync({ type: "blob" });
        }).then((content) => {
          const link = document.createElement("a");
          link.href = URL.createObjectURL(content);
          link.download = decodeURIComponent(fileName);
          link.click();
          URL.revokeObjectURL(link.href);
          ElMessage({
            type: 'success',
            message: '导出成功',
          });
        }).catch((error) => {
          console.error('解压失败，直接下载原文件:', error);
          // 如果解压失败，直接下载原文件
          const link = document.createElement("a");
          link.href = URL.createObjectURL(blob);
          link.download = decodeURIComponent(fileName);
          link.click();
          URL.revokeObjectURL(link.href);
          ElMessage({
            type: 'success',
            message: '导出成功',
          });
        });
      });
    } else {
      // 非zip文件或JSZip不可用，直接下载
      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = decodeURIComponent(fileName);
      link.click();
      URL.revokeObjectURL(link.href);
      ElMessage({
        type: 'success',
        message: '导出成功',
      });
    }
  } catch (error) {
    console.error('下载文件失败:', error);
    ElMessage({
      type: 'error',
      message: '下载文件出现错误，请联系管理员！',
    });
  }
}
